package com.meeruu.sg.account.core.domain.biz.task;

import com.alibaba.schedulerx.worker.domain.JobContext;
import com.alibaba.schedulerx.worker.processor.JavaProcessor;
import com.alibaba.schedulerx.worker.processor.ProcessResult;
import com.meeruu.boot.ucs.datasource.redis.IRedisCache;
import com.meeruu.common.utils.LoggerUtil;
import com.meeruu.common.utils.spring.SpringCtxUtils;
import com.meeruu.sg.account.core.api.exception.AccountException;
import com.meeruu.sg.account.core.api.exception.ErrorCode;
import com.meeruu.sg.account.core.domain.biz.ConfigUserWithdrawBiz;
import com.meeruu.sg.account.core.domain.biz.SysCoreConfigBiz;
import com.meeruu.sg.account.core.domain.model.ConfigUserWithdraw;
import com.meeruu.sg.account.core.domain.model.SysCoreConfig;
import com.meeruu.sg.account.core.domain.model.cache.CacheKeys;
import com.meeruu.summerframework.cloud.event.SummerEventListener;
import com.meeruu.summerframework.cloud.event.SummerReadyEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Slf4j
@Component
public class LoadCoreConfigTask extends JavaProcessor implements SummerEventListener<SummerReadyEvent> {

    private IRedisCache iRedisCache;

    @Autowired
    private SysCoreConfigBiz sysCoreConfigBiz;

    @Autowired
    private ConfigUserWithdrawBiz configUserWithdrawBiz;

    @Override
    public void onEvent(SummerReadyEvent summerReadyEvent) {
        load ();
    }

    @Override
    public ProcessResult process(JobContext jobContext) throws Exception {
        try {
            load();
            return new ProcessResult(true);
        } catch (Exception e) {
            LoggerUtil.error(log, "加载系统配置失败", e);
            return new ProcessResult(false);
        }
    }

    /***
     * 每分钟重新加载一次系统配置
     */
    public boolean load() {
        iRedisCache = SpringCtxUtils.getBean("ucs.redis-wrapper.default");
        LoggerUtil.info(log, "加载系统配置开始");

        try {
            if (!iRedisCache.lock(CacheKeys.KEY_LOCK_SYS_CONFIG_LOAD, 30)) {
                LoggerUtil.warn(log, "加载系统配置锁竞争失败");
                return false;
            }
            /** 加载全局系统配置 */
            loadSysCoreConfig();

            /** 加载用户提现限制配置 */
            loadUserWithdrawConfig();

            LoggerUtil.info(log, "加载系统配置结束");
            return true;
        } catch (Exception e) {
            throw e;
        } finally {
            iRedisCache.unlock(CacheKeys.KEY_LOCK_SYS_CONFIG_LOAD);
        }
    }


    /***
     * 加载用户提现限制配置
     */
    private void loadUserWithdrawConfig() {
        try {
            List<ConfigUserWithdraw> configs = configUserWithdrawBiz.queryAll();
            if (CollectionUtils.isEmpty(configs)) {
                iRedisCache.remove(CacheKeys.KEY_USER_WITHDRAW_CONFIG);
                return;
            }
            if (iRedisCache.set(CacheKeys.KEY_USER_WITHDRAW_CONFIG, configs)) {
                LoggerUtil.info(log, "加载用户提现限制配置成功");
            } else {
                throw new AccountException(ErrorCode.LOAD_SYS_ERROR.getCode(), "加载用户提现限制配置失败");
            }
        } catch (Exception e) {
            throw new AccountException(ErrorCode.LOAD_SYS_ERROR.getCode(), "[加载用户提现限制配置失败]" + e.getMessage());
        }
    }

    /***
     * 加载全局系统配置
     */
    private void loadSysCoreConfig() {
        try {
            List<SysCoreConfig> configs = sysCoreConfigBiz.queryAll();
            if (CollectionUtils.isEmpty(configs)) {
                iRedisCache.remove(CacheKeys.KEY_SYS_CONFIG);
                return;
            }
            if (iRedisCache.set(CacheKeys.KEY_SYS_CONFIG, configs)) {
                LoggerUtil.info(log, "系统全局配置加载成功");
            } else {
                throw new AccountException(ErrorCode.LOAD_SYS_ERROR.getCode(), "加载全局系统配置失败");
            }
        } catch (Exception e) {
            throw new AccountException(ErrorCode.LOAD_SYS_ERROR.getCode(), "[加载全局系统配置失败]"+e.getMessage());
        }
    }
}
